package com.mowh.multithreading.active.object.executors.active.object;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/**
 * @author mowh1gd
 * @create 2023/11/30 11:04
 */
class ActiveObjectImpl implements ActiveObject {//实现了Proxy和Servant角色
    private final ExecutorService executorService = Executors.newSingleThreadExecutor();//单线程，作为scheduler角色，隐藏了ActivationQueue和Servant角色以及执行操作。
    @Override
    public Future<String> makeString(int count, char fillChar) {
        class MakeStringRequest implements Callable<String> {//producer:继承Callable
            @Override
            public String call() {
                char[] buffer = new char[count];
                for (int i = 0; i < count; i++) {
                    buffer[i] = fillChar;
                    try {
                        Thread.sleep(100);
                    } catch (InterruptedException e) {
                    }
                }
                return new String(buffer);
            }
        }
        return executorService.submit(new MakeStringRequest());//调用：submit
    }

    @Override
    public void displayString(String s) {
        class DisplayStringRequest implements Runnable {//producer:继承Runnable
            @Override
            public void run() {
                try {
                    System.out.println("display: " + s);
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                }
            }
        }
        executorService.execute(new DisplayStringRequest());//调用：execute
    }

    @Override
    public void shutdown() {
        executorService.shutdown();
    }
}
